package io.jft.doll.ui.address

import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.extend.observeEx
import com.g.base.extend.resultNotNull
import com.g.base.help.observeSimpleNotify
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.Status
import com.g.base.router.RouteExtras
import com.g.base.ui.BaseActivity
import com.g.base.ui.recyclerView.MultiTypeAdapter
import com.g.base.ui.recyclerView.decoration.LinearItemDecoration
import com.g.base.ui.recyclerView.item.BaseItem
import com.g.base.ui.recyclerView.setupRecyclerView
import io.jft.doll.R
import io.jft.doll.databinding.ActivityAddressBinding
import io.jft.doll.event.NotifyUrl
import io.jft.doll.model.bindModel.AddressBind
import io.jft.doll.model.viewModel.AddressViewModel
import io.jft.doll.room.entity.common.AddressItemCEntity
import io.jft.doll.router.RouterPage

/**
 * Created by G on 2017/8/23 0023.
 */
@Route(path = RouterPage.AddressActivity, extras = RouteExtras.NeedOauth)
class AddressActivity : BaseActivity<ActivityAddressBinding>() {
    override var hasToolbar: Boolean = true

    @Autowired
    @JvmField
    var isSelectModel = false

    private lateinit var adapter: MultiTypeAdapter
    private val addressViewModel by lazy { AddressViewModel() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setContentView(R.layout.activity_address)
        //recyclerView初始化
        setupView()
        //新建一个
        contentView.newAddr.setOnClickListener {
            ARouter.getInstance().build(RouterPage.AddressChangeActivity).withObject("addressItem", AddressItemCEntity()).navigation(this)
        }

        //观测数据
        obsData()
        //获取数据
        addressViewModel.operateAllAddress(false)
        //应该刷新了
        observeSimpleNotify<Any?>(this, NotifyUrl.AddressActivity) {
            addressViewModel.operateAllAddress(true)
            true
        }
    }

    private fun setupView() {
        adapter = setupRecyclerView(contentView.recyclerView)
        contentView.recyclerView.addItemDecoration(LinearItemDecoration(this))
        //Toolbar处理
        toolbar.title = if (isSelectModel) "选择收货地址" else "收货地址"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener {
            finishAfterTransition()
        }

        if (isSelectModel) {
            toolbar.inflateMenu(R.menu.address_edit)
            toolbar.setOnMenuItemClickListener {
                ARouter.getInstance().build(RouterPage.AddressActivity).navigation(this)
                return@setOnMenuItemClickListener true
            }
        }
    }

    override fun onReload() {
        addressViewModel.operateAllAddress(true)
    }

    override fun onTokenChange(data: UserEntity?) {
        if (data == null) {
            showNeedOauth()
        } else {
            showContentView()
            addressViewModel.operateAllAddress(true)
        }
    }

    private fun obsData() {
        addressViewModel
                .obsAllAddress()
                .resultNotNull()
                .observeEx(this) {
                    when (it.status) {
                        Status.Loading -> {
                            showLoading()
                        }
                        Status.Content -> {
                            applyData(it.data!!)
                            showContentView()
                        }
                        Status.Error -> {
                            if (it.error?.code == com.g.base.api.ErrorCode.EMPTY) {
                                applyData(listOf())
                                showEmpty("请先添加一个收货地址")
                            } else {
                                showError(it.error?.message ?: "加载错误 点击重试")
                            }
                        }
                    }
                }
    }

    private fun applyData(newData: List<AddressItemCEntity>) {
        adapter.diffItems.addAll(newData.map {
            AddressBind(it, isSelectModel, false)
                    .also { holder ->
                        holder.setOnClickListener { _ ->
                            if (isSelectModel) {
                                addressViewModel.updateSelect(it)
                                finishAfterTransition()
                            } else {
                                ARouter.getInstance().build(RouterPage.AddressChangeActivity)
                                        .withObject("addressItem", it).navigation(this)
                            }
                        }
                    }
        })

        adapter.calcDiffAndDispatchUpdate(
                { oldItem: BaseItem<*>, _: Int, newItem: BaseItem<*>, _: Int ->
                    (oldItem as AddressBind).beanItem.get()?.id == (newItem as AddressBind).beanItem.get()?.id
                },
                { oldItem: BaseItem<*>, _: Int, newItem: BaseItem<*>, _: Int ->
                    (oldItem as AddressBind).beanItem == (newItem as AddressBind).beanItem
                })
    }
}
